//
//  JigSawKioskTextOutput.m
//  OutputTextHandlingTest
//
//  Created by Blossom on 10-10-17.
//  Copyright 2010 Miles Thorogood, greenmeat.net. All rights reserved.
//

#import "JigSawKioskTextOutput.h"


@implementation JigSawKioskTextOutput
- (id) init {
	
	self = [super init];
	[self setDirectoryToWriteTo: (NSString *) @"/Users/Shared/Kiosk/"];
	[self setFileToWriteTo:(NSString *)@"kioskWrittenFeedback"];
	
	return self;
	
}

- (id)initWithDirectoryPath: (NSString *) outputDirectoryPath 
									   AndFileToWriteTo:(NSString *) outputFilename {
	
	self = [super init];
	[self setDirectoryToWriteTo: outputDirectoryPath];
	[self setFileToWriteTo: outputFilename];	
	
	return self;
}

-(void)dealloc
{
	[directoryToWriteTo release];
	[fileToWriteTo release];
	[super dealloc];
	
}


- (void)recordFeedbackInformationToFile:(NSString *) videoWatched 
									   dateWatched:(NSString *) date
									   nameOfWatcher:(NSString *) name
									   emailAddressOfWatcher:(NSString *) emailAddress
									   writtenFeedbackFromComment:(NSString *) writtenFeedback 
									   FeedbackVideoFilename:(NSString *) videoFeedback {
	
	
	//Creat the entry to write to the file
	NSString *testDataString = [NSString stringWithFormat:@" %@, %@, %@, %@, %@, %@ \n",
								videoWatched, date, name, emailAddress, writtenFeedback, videoFeedback]; 
	NSData *data = [testDataString dataUsingEncoding:NSUTF8StringEncoding];
	
	//Open the file TODO check the directory and filename concatenate into an actual filename
	NSString *path = [NSString stringWithFormat:@"%@%@", directoryToWriteTo, fileToWriteTo];
	outputDataFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path]; 
	
	//Check if the file opened successfully
	if (outputDataFileHandle == nil) {
		//If not, assume the file does not exist and create it
		
		//Create header content		
		NSString *headerString = @"Video watched, Date Watched, Name, Email Address, Comment, Video Recording \n";
		NSData *headerData = [headerString dataUsingEncoding:NSUTF8StringEncoding];
		
		//Create File
		dataFileManager = [[NSFileManager alloc] init];
		[dataFileManager createFileAtPath:path contents:headerData attributes:nil];
		
		//set up the file handle
		outputDataFileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
		
		if(outputDataFileHandle == nil) //abort
			NSLog(@"Not able to create outputFile in JigSawKioskTextOutput");
	}
	
	//move file pointer to the end of the file so data is appended to file and existing content is not be lost
	[outputDataFileHandle seekToEndOfFile]; 
	
	[outputDataFileHandle writeData:data];
	
	[outputDataFileHandle closeFile];
}

@synthesize directoryToWriteTo;
@synthesize fileToWriteTo;
@synthesize dataFileManager; 
@synthesize outputDataFileHandle;


@end
